import { http } from '@/utils/http'
import {usePmAppStore} from "@/stores";
import {gotoH5PasskeyLogin} from "@/interceptors/route";

export function usePmLoginApi() {
  return {
    socialLogin(loginParam: PmLoginParams) {
      return http.post('/prod-api/admin-api/system/auth/social-login', loginParam)
    },
    // 获取用户详细信息
    getInfo() {
      return http.get('/prod-api/admin-api/system/auth/get-permission-info')
    },
    logout() {
      return http.post('/prod-api/admin-api/system/auth/logout')
    },
    refreshToken<T = any>() {
      return new Promise<IResData<T>>((resolve, reject) => {
        uni.request({
          url: '/prod-api/admin-api/system/auth/refresh-token?refreshToken=' + usePmAppStore().getRefreshToken(),
          method: 'POST',
          dataType: 'json',
          // #ifndef MP-WEIXIN
          responseType: 'json',
          // #endif
          // 响应成功
          success(res) {
            const data = res.data as IResData<T>
            if (data.code !== 0) {
              uni.showModal({
                title: '提示',
                content: data.msg || '请求错误',
                success: () => {
                  gotoH5PasskeyLogin()
                  resolve(res.data as IResData<T>)
                },
                fail: () => {
                  gotoH5PasskeyLogin()
                  resolve(res.data as IResData<T>)
                }
              })
            } else {
              resolve(res.data as IResData<T>)
            }
          },
          // 响应失败
          fail(err) {
            gotoH5PasskeyLogin()
            uni.showModal({
              title: '提示',
              content: JSON.stringify(err) || '请求错误',
            })
            reject(err)
          },
        })
      })
    }
  }
}
